<?php
namespace app\admin\controller\shop;

use addons\mall\model\Spec;
// use app\admin\controller\Addon;

use app\admin\model\shop\Category;
use app\admin\model\shop\Goods as GoodsModel;
use app\admin\model\shop\GoodsValue as GoodsValueModel;
use app\admin\service\TriggerService;
use app\common\constants\AdminConstant;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Request;
use app\admin\model\shop\Spec as SpecModel;
use think\facade\Db;

use function GuzzleHttp\json_decode;
use Dopic;
use Imgcompress;
/**
 * Class Back
 * @package app\admin\controller\Addon
 * NotParse
 */
class Goods extends AdminController
{    
    
    public function __construct(App $app)
    {
        parent::__construct($app);
        // 规格魔板
        $this->model=new GoodsModel();
        $this->spec=new SpecModel();
        $this->category=new Category(); 
        $this->GoodsValueModel =new GoodsValueModel();
    }

    /**
     * 基类文件use app\admin\controller\Addon;
     *
     */
    public function index()
    {      
      
        
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
        
            $count = $this->model
                ->withJoin([
                    'cate'	=>	['cate_name']
                ])
                ->where($where)->fetchsql(false)
                ->count();
             
            $list = $this->model
                ->withJoin([
                    'cate'	=>	['cate_name']
                ])
                ->where($where)
                ->page($page, $limit)
                ->order('create_time desc')
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }

        return $this->fetch();
    }
    /**
     */
    public function stock()
    {
        $products_id  = Request::param('products_id');
        $row = $this->model->where('products_id',$products_id)->find();
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $post['total_stock'] = $row->total_stock + $post['stock'];
                $post['stock']       = $row->stock + $post['stock'];
                $save                = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * 
     */
    public function add()
    {   
        if ($this->request->isAjax()) {
            $post                = $this->request->post();
            
            // $authIds          = $this->request->post('auth_ids', []);
            // $post['auth_ids'] = implode(',', array_keys($authIds));
            $rule             = [];
            $this->validate($post, $rule);
            if(isset($post['spec_item'])){
                $post['spec_item']=implode(',',$post['spec_item']);
            }

            $data=$this->getData($post);
       
            $post=$data['data'];
            $post['product_value']=$data['product_value'];
            $post['total_stock']=array_sum(array_column($data['product_value'],'stock'));
       
            Db::startTrans();
            try {
                $save = $this->model->save($post);
                Db::commit();
            } catch (\Exception $e) {
                $this->error($e->getMessage());
                Db::rollback();
            }
            // dd($post);
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }

        return $this->fetch();
    }
    //数据处理
    public function getData($post){
        $list=[];
       if(empty($post['cate_id']) && isset($post['products_id'])){
          $post['cate_id']=Db::name('goods')->where('products_id',$post['products_id'])->value('cate_id');
       }
       
        if($post['spec_type']=="one"){//单规格
            $data=$post;
            $data['price']=min($post['price']);
            $data['activity_price']=min($post['activity_price']);
            $product_value[]=[
                'price'          =>$post['price'][0],
                'activity_price' =>$post['activity_price'][0],
                'stock'          =>$post['stock'],
                'total_stock'          =>$post['stock'],
            ];
            $list['data']=$data;
            $list['product_value']=$product_value;    
        }else{
            $data=$post;
            $flag=false;
            
            if($post['skus']){
                foreach ($post['skus'] as $k => $v) {
                    $sku_val="";
                    foreach (explode(',',$k) as $k1 => $v1) {

                         $sku_val.= "_". Db::name('goods_spec')->where('a.cate_id',$post['cate_id'])->whereIn('a.id',$post['specs'])->where('b.item',$v1)->alias('a')->join('goods_spec_item b','a.id=b.spec_id')->value('b.id');
                         
                    }
                   
                    $sku_val=array_filter(explode('_',$sku_val));
                   
                
                    sort($sku_val);
                    $image='';
                    if(isset($post['products_id'])){
                        $image=Db::name('goods_value')->where('products_id',$post['products_id'])->where('sku_val',implode('_',$sku_val))->value('image');
                    }
                    $flag=true;
                    if($flag){
           
                        $product_value[]=[
                            'price'          =>$v['price'],
                            'activity_price' =>$v['activity_price'],
                            'stock'          =>$v['stock'],
                            'total_stock'    =>$v['stock'],
                            'sku'            =>$k,
                            'sku_val'        =>implode('_',$sku_val),
                            'image'          =>$v['picture']?$v['picture']:$image,
                        ];
                   }
                }
            }
            $data['specs']=array_unique($data['specs']);
            $data['price']=min(array_column($product_value,'price'));
            $data['activity_price']=min(array_column($product_value,'activity_price'));
            $list['data']=$data;
            $list['product_value']=$product_value;
        }
    
        return $list;
    }
    public function edit()
    {
        $products_id  = Request::param('products_id');
        $row = $this->model->where('products_id',$products_id)->find();

        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            
            $rule = [];
            $this->validate($post, $rule);
            if(isset($post['spec_item'])){
                $post['spec_item']=implode(',',$post['spec_item']);
            }
            
            $data=$this->getData($post);
           
            $post=$data['data'];
            $post['product_value']=$data['product_value'];
            $post['total_stock']=array_sum(array_column($data['product_value'],'stock'));
           
            Db::startTrans();
            try {
                $save = $row->save($post);
                Db::commit();
            } catch (\Exception $e) {
                $this->error($e->getMessage());
                // 回滚事务
                Db::rollback();
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
      
         $cate=$this->category->getCate($row['cate_id']);
     
        $specs=$this->spec->getSpec($row['cate_id']);

        $this->assign([
            'cate'      =>$cate,
            'specs'     =>$specs,
            'row'       =>$row,
        ]);
      
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="删除")
     */
    public function delete()
    {   
        $products_id  = Request::param('products_id');
        if(Request::param('id')){
            $products_id=Request::param('id');
        }
        $row = $this->model->whereIn('products_id', $products_id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        Db::startTrans();
        try {
            foreach ($row as $k => $v) {
                del_image($v['cover_picture']);
                del_image($v['videoUrl']);
                $main_picture=$v['main_picture']?explode('|',$v['main_picture']):'';
                if($main_picture){
                    foreach ($main_picture as $main) {
                        del_image($main);
                    }
                }
                $detail_picture=$v['detail_picture']?explode('|',$v['detail_picture']):'';
                if($detail_picture){
                    foreach ($detail_picture as $detail) {
                        del_image($detail);
                    }
                }
            }
            $save = $row->delete();
            $this->GoodsValueModel->whereIn('products_id',$products_id)->delete();
            Db::commit();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
        }
        $save ? $this->success('删除成功') : $this->error($e->getMessage());
    }
    public function modify()
    {
        $post = $this->request->post();
        $rule = [
            // 'cate_id|ID'    => 'require',
            'field|字段' => 'require',
            'value|值'  => 'require',
        ];
        $this->validate($post, $rule);
        // if (!in_array($post['field'], $this->allowModifyFields)) {
        //     $this->error('该字段不允许修改：' . $post['field']);
        // }
        $row = $this->model->where('products_id',$post['id'])->find();
        empty($row) && $this->error('数据不存在');
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }
    public function getGoods(){
            $post = $this->request->param();
         
            $where['store_id']=$post['store_id'];
            $where['is_shelves']=1;
            $list  = $this->model->field('products_title,products_id')->order('products_id asc')->where($where)->select();
            $data  = [
                'code'  => 1,
                'msg'   => '',
                'data'  => $list,
            ];
            return json($data);
    }
     //生成文件名称
     public function newName(){
    	//生成随机文件名
    	$hash = "compress-";
    	//定义一个包含大小写字母数字的字符串
    	$chars = "123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
    	//把字符串分割成数组
    	$nchars = str_split($chars);
    	//打乱数组
    	shuffle($nchars);
    	//从数组中随机取出15个字符
    	$chars_key = array_rand($nchars,15);
        
        $fchar='';
    	//把取出的元素重新组成字符串
    	for ($i=0; $i < 15; $i++) { 
    		$fchar .= $nchars[$chars_key[$i]];
    	}
        
    	return $hash.md5($fchar.time().(double)microtime()*1000000);
    }
    // 图片压缩
    public function compression($source){
            // $source =  'http://mango.com/upload/20220708/abedf1ab9f36df5686c0cb309a70f076.png';//原图片名称
            $dst_img = $this->newName();//压缩后图片的名称
            $percent = 1;  #原图压缩，不缩放，但体积大大降低
            $image = (new imgcompress($source,$percent))->compressImg($dst_img);
            $image=str_replace('./','',$image);
            $image=\think\facade\Request::domain()."/".$image;
            return $image;
    }
    //商品复制
    public function copy(){

        if ($this->request->isAjax()) {
            $post = $this->request->post();
          
            // 图片分割
            // $dopic=new Dopic(ROOT_PATH,"https://www.chemeijia.com/uploads/images/20220403/472d7fe55ed3e7cc3a133ae5f91e6f6c.jpg",'./upload/');
            // $image=$dopic->explodepic();
            // $this->error('该功能正在维护中,暂停使用');
            $where=[
                ['store_id','=',$post['store_id']]
            ];
            if($post['store_id']==$post['news_store_id']){
                $this->error('粘入门店选择错误');
            }
            $weh=[
                ['store_id','=',$post['news_store_id']]
            ];
            if($post['type']==1){
                if(empty($post['products_id'])){
                    $this->error('请选择商品');
                }
                array_push($where,['products_id','in',$post['products_id']]);
            }else{
                $this->error('暂不支持复制分类下的商品');
                array_push($where,['cate_id','=',$post['cate_id']]);
               
            }
          
            $data=[];
            $row = $this->model->where($where)->select()->toArray();
           
            // dump($post);
            // dd($row);
            foreach ($row as $v) {
                $is_prod=Db::name('store_product')->where('store_id',$post['news_store_id'])->where('products_title',$v['products_title'])->find(); 
                if($is_prod) $this->error("<span style='color:red;font-weight:800'>【".$v['products_title'].'】</span>商品已存在！！！');
            }
        
            Db::startTrans();
            try {
                foreach ($row as &$v) {
                 
                    if($v['videoUrl']){
                        $videoUrl=$this->saveFile($v['videoUrl']);
                        $v['videoUrl']=$videoUrl;
                    }
                    if($v['cover_picture']){
                        $cover_picture=$this->saveFile($v['cover_picture']);
                        dd($cover_picture);
                        $v['cover_picture']=$cover_picture;
                    }
                    if($v['main_picture']){
                        $main_picture=$this->saveFile($v['main_picture']);
                        $v['main_picture']=$main_picture;
                    }
                    if($v['detail_picture']){
                        $detail_picture=$this->saveFile($v['detail_picture']);
                        $v['detail_picture']=$detail_picture;
                    }
                    if($v['brand_id']){
                        $barand_name=Db::name('brand')->where('id',$v['brand_id'])->value('brand_name');
                        $brand_id=Db::name('brand')->where('brand_name',$barand_name)->where('store_id',$post['news_store_id'])->value('id');
                        $v['brand_id']=$brand_id;
                    }
                    $store_cate_name=Db::name('store_category')->where('store_category_id',$v['cate_id'])->value('cate_name');
                    $new_cate_id=Db::name('store_category')->where('store_id',$post['news_store_id'])->where('cate_name',$store_cate_name)->value('store_category_id');
                   
                    if(!$new_cate_id){
                        $old_cate_name=Db::name('store_category')->where('store_category_id',$v['cate_id'])->value('cate_id');
                        $new_cate_id=Db::name('store_category')->where('store_id',$post['news_store_id'])->where('cate_id',$old_cate_name)->value('store_category_id');
                    }
                    
                
                    if(empty($new_cate_id) || $new_cate_id==null)throw new \Exception('分类不存在，请检查后再试');
                 
                    $v['store_id']=$post['news_store_id'];
                    $v['cate_id']=$new_cate_id;
                    $sku_val='';
                    $specs_value='';
                    $product_value=$this->productValue->where('products_id',$v['products_id'])->select()->toArray();
                    if($v['spec_type']=="more"){
                        foreach ($product_value as $kk => $vv) {
                            if($vv['image']){
                                $iamge_spec=$this->saveFile($vv['image']);
                                $product_value[$kk]['image']=$iamge_spec;
                            }
                            $new_sku_val=[];
                            if($vv['sku_val']){
                                $spec_item=Db::name('spec_item')->whereIn('id',explode('_',$vv['sku_val']))->select()->toArray();
                               
                                foreach ($spec_item as $k1 => $v1) {
                                    if($v1['spec_id']!=120){
                                            $old_spec=Db::name('spec')->where('id',$v1['spec_id'])->value('title');
                                            
                                            $new_spec=Db::name('spec')->where('cate_id',$new_cate_id)->where('title',$old_spec)->value('id');
                                            if($new_spec==null || empty($new_spec))throw new \Exception('分类下的规格不存在，请检查后再试');
                                            $new_item=Db::name('spec_item')->where(['spec_id'=>$new_spec,'item'=>$v1['item']])->find();
                                            
                                            if(empty($new_item)){
                                                $spec_item_id=Db::name('spec_item')->insertGetId(['spec_id'=>$new_spec,'item'=>$v1['item']]);
                                                array_push($new_sku_val,$spec_item_id);
                                            }else{
                                                array_push($new_sku_val,$new_item['id']);
                                            }
                                    }
                                    if(in_array($v1['id'],[1881,1882,1883])) array_push($new_sku_val,$v1['id']);
                                    
                                }
                                sort($new_sku_val);
                                $specs_value.=implode('_',$new_sku_val)."_";
                                $product_value[$kk]['sku_val']=implode('_',$new_sku_val);
                            }   
                        } 
                        $specs_value=array_filter(explode('_',$specs_value));
                        $newSpecItems=Db::name('spec_item')->whereIn('id',$specs_value)->column('spec_id,item');
                        $specs=array_unique(array_column($newSpecItems,'spec_id'));
                        $specs=implode(',',$specs);
                        $v['specs']=$specs;
                        $tempNewSpecItems=[];
                        foreach ($newSpecItems as $k2 => $v2) {
                            $tempNewSpecItems[$v2['spec_id']][]=$v2;
                        }
                        $tempNewSpecItemsArr=[];
                        foreach ($tempNewSpecItems as $k3 => $v3) {
                            $name=Db::name('spec')->where('id',$k3)->value('title');
                            foreach ($v3 as $k4 => $v4) {
                                $tempNewSpecItemsArr[$name][]=$v4['item'];
                            }
                        }
                        
                        $v['specs_value']=$tempNewSpecItemsArr;
                        
                        $skus=[];
                        foreach ($product_value as $k5 => $v5) {
                            $skus[$v5['sku']]=[
                                'picture'=>$v5['image'],
                                'price'=>$v5['price'],
                                'member_price'=>$v5['member_price'],
                                'activity_price'=>$v5['activity_price'],
                                'stock'=>$v5['stock'],
                                'price_show'=>$v5['price_show']==1?"on":'off',
                                'member_show'=>$v5['member_show']==1?"on":'off',
                                'activity_show'=>$v5['activity_show']==1?"on":'off',
                            ];
                        }
                    
                        $v['skus']=$skus;
                }
                    unset($v['products_id']);
                    $v['update_time']=time();
                    $save = $this->model->save($v);
              
                    foreach ($product_value as $k6 => $v6) {
                        $product_value[$k6]['products_id']=$this->model->products_id;
                    }
                    Db::name('store_product_value')->insertAll($product_value);
                }
              
                // $rule = [];
                // $this->validate($data, $rule);
                // $save = $this->model->saveAll($data);
                Db::commit();
            } catch (\Exception $e) {
                $this->error($e->getMessage());
           
                Db::rollback();
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }
    //文件处理
    public function saveFile($url){
        $urlArr=explode('|',$url);
       
        $str_url=[];
        foreach ($urlArr as $k => $v) {
         
            $image_url=str_replace(\think\facade\Request::domain(),str_replace("..\\",'',ROOT_PATH),$v);
          
            if(strpos($image_url,\think\facade\Request::domain()) !== false){ 
                if(file_exists($image_url)){
                    $newimage=$this->downLoadNetWorkFile($image_url);
                    $newsUrl=str_replace('./upload/',\think\facade\Request::domain().'/upload/',$newimage['save_path']);
                    array_push($str_url,$newsUrl);
                }
            }else{
                if($this->file_exists($v)){
                    $newimage=$this->downLoadNetWorkFile($v);
                    $newsUrl=str_replace('./upload/',\think\facade\Request::domain().'/upload/',$newimage['save_path']);
                    array_push($str_url,$newsUrl);
                } 
            }   
        }
         if($str_url){
             return implode('|',$str_url);
         }
         return '';
    }
    //检查远程文件是否存在
   public function file_exists($url){

        $ch = curl_init();

        curl_setopt($ch,CURLOPT_URL,$url);

        curl_setopt($ch,CURLOPT_NOBODY, 1); // 不下载

        curl_setopt($ch,CURLOPT_FAILONERROR, 1);

        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);

        if(curl_exec($ch)!==false)

        return true;

        else

        return false;

    }
     /**
     * php完美实现下载远程图片保存到本地
     * 参数：文件url,保存文件目录,保存文件名称，使用的下载方式
     * @param $url
     * @param string $save_dir
     * @param string $type
     * @return mixed
     * @throws ParameterException
     * @author:  deng    (2019/4/24 11:36)
     */
    public static function downLoadNetWorkFile($url, $save_dir = '',$type = '0')
    {
        if (empty($url)) throw new \think\Exception('图片地址不能为空！');
        if (empty($save_dir)) $save_dir = './';

        //  获取文件后缀  eg: .png
        $ext = strrchr($url, '.');
    
        // if ($ext != '.png' && $ext != '.jpg' && $ext != '.gif') {
        //     //  图片路径不是正常格式时，默认png
        //     $file_name = md5(microtime(true)).'.png';
        // } else {
            // $file_name = time().mt_rand(1000,9999).$ext;
            $file_name=md5(microtime(true)).$ext;
        // }
        
        if(0!==strrpos($save_dir,'/')){
            $save_dir.='upload/'.date('Ymd').'/';
        }

        //  创建保存目录
        if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
            throw new \think\Exception('没有上传图片的权限');
        }
        
        $result = self::downFile($url, $save_dir, $file_name, $type);
      
        return $result;
    }
      /**
     * 获取远程文件所采用的方法
     * @param $url
     * @param $save_dir
     * @param $filename
     * @param string $type
     * @return array
     * @author:  deng    (2019/4/24 14:38)
     */
    private static function downFile($url, $save_dir, $filename, $type = '0')
    {
        if($type){
            $ch=curl_init();
            $timeout=5;
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
            $img=curl_exec($ch);
            curl_close($ch);
        }else{
            ob_start();
            readfile($url);
            $img=ob_get_contents();
            ob_end_clean();
        }
        $size=strlen($img);
        //文件大小
        $fp2=@fopen($save_dir.$filename,'a');
        fwrite($fp2,$img);
        fclose($fp2);
        unset($img,$url);

        $result = [
            'file_size' => $size,
            'file_name' => $filename,
            'save_path' => $save_dir.$filename,
            'address' => $save_dir.$filename
        ];
        return $result;
    }
    function getProductAttr(){
        $post = $this->request->get();
        $where['products_id']=$post['products_id'];
        $list  =$this->productValue->field('sku')->where($where)->select();
    
        $data  = [
            'code'  => 1,
            'msg'   => '',
            'data'  => $list,
        ];
        return json($data);
    }
}


